//
//  AliOSSObjctManage.m
//  VideoExam
//
//  Created by apple on 2020/4/8.
//

#import "AliOSSObjctManage.h"
@interface AliOSSObjctManage ()
@property(nonatomic,strong)OSSClient * client;
@property(nonatomic,strong)OSSTask * putTask;
@end
@implementation AliOSSObjctManage
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static AliOSSObjctManage *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        NSString *endpoint = @"http://oss-cn-beijing.aliyuncs.com";
        NSString * url = oss_url;
        id<OSSCredentialProvider> credential = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:url];
        _client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
        
//        id<OSSCredentialProvider> credential = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:@"应用服务器地址，例如http://abc.com:8080"];
//        client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
        
        
//        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OSS_AccessKey secretKey:OSS_SecretKey];
//         _client = [[OSSClient alloc] initWithEndpoint:OSS_Endpoint credentialProvider:credential];
    }
    return self;
}
- (void)uploadVideoWithVideoPath:(NSString *)videoPath urlName:(NSString *)urlName progressBlock:(void(^)(CGFloat progress))progressBlock Success:(void(^)(NSString * videoUrlStr))successBlock error:(void(^)(void))errorBlock {
        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
         //上传表名字
         put.bucketName = OSS_BucketName;
    //上传视频名
        NSString * objectKey=urlName;
        put.objectKey = objectKey;
        put.uploadingFileURL = [NSURL fileURLWithPath:videoPath];//通过路径长传文件
//        NSData *imageData = UIImageJPEGRepresentation(self.model.inchPhoto_2, 0.5);
//        put.uploadingData=imageData;
        // 可选字段，可不设置
        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                 CGFloat pr =(CGFloat) totalByteSent/totalBytesExpectedToSend;
                if (progressBlock) {
                    progressBlock(pr);
                }
             NSLog(@"%lld, %lld, %lld  进度%f", bytesSent, totalByteSent, totalBytesExpectedToSend,pr);
            }];          
        };
        // 以下可选字段的含义参考： https://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
        // put.contentType = @"";
        // put.contentMd5 = @"";
        // put.contentEncoding = @"";
        // put.contentDisposition = @"";
        // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil]; // 可以在上传时设置元信息或者其他HTTP头部
        OSSTask * putTask = [self.client putObject:put];
        @weakify(self);
        [putTask continueWithBlock:^id(OSSTask *task) {
             @strongify(self);
            if (!task.error) {
               task = [self.client presignPublicURLWithBucketName:OSS_BucketName
                withObjectKey:objectKey];
                if (!task.error) {
                      [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        if (successBlock) {
                                successBlock(task.result);
                        }
                      }];
                } else {
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        if (errorBlock) {
                            errorBlock();
                        }
                    }];
                }
            } else {
                  NSLog(@"视频上传错误: %@" , task.error);
               [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    if (errorBlock) {
                       errorBlock();
                     }
                }];
            }
            return nil;
        }];
  
}
- (NSString *)getVideoUrl_objectKey:(NSString *)objectKey {
    NSString *url=nil;
   OSSTask * task = [self.client presignPublicURLWithBucketName:OSS_BucketName
                             withObjectKey:objectKey];
    if (!task.error) {
        url=task.result;
    }
    return url;
}

//+(void)uploadVideoWithVideoPath:(NSString *)videoPath client:(OSSClient *)client progressBlock:(void(^)(CGFloat progress))progressBlock Success:(void(^)(NSString * videoUrlStr))successBlock error:(void(^)(void))errorBlock {
//        OSSPutObjectRequest * put = [OSSPutObjectRequest new];
//         //上传表名字
//         put.bucketName = OSS_BucketName;
//    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
//    formatter.dateFormat=@"yyyyMMddHHmmss";
//    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
//    NSString *flieName =[NSString stringWithFormat:@"userVideo/%@.mp4",dateStr];
//    //上传视频名
//        NSString * objectKey=flieName;
//        put.objectKey = objectKey;
//        put.uploadingFileURL = [NSURL fileURLWithPath:videoPath];//通过路径长传文件
////        NSData *imageData = UIImageJPEGRepresentation(self.model.inchPhoto_2, 0.5);
////        put.uploadingData=imageData;
//        // 可选字段，可不设置
//        put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//            // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
//            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                 CGFloat pr =(CGFloat) totalByteSent/totalBytesExpectedToSend;
//                if (progressBlock) {
//                    progressBlock(pr);
//                }
//             NSLog(@"%lld, %lld, %lld  进度%f", bytesSent, totalByteSent, totalBytesExpectedToSend,pr);
//            }];
//        };
//        // 以下可选字段的含义参考： https://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
//        // put.contentType = @"";
//        // put.contentMd5 = @"";
//        // put.contentEncoding = @"";
//        // put.contentDisposition = @"";
//        // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil]; // 可以在上传时设置元信息或者其他HTTP头部
//        OSSTask * putTask = [client putObject:put];
//        [putTask continueWithBlock:^id(OSSTask *task) {
//            task = [client presignPublicURLWithBucketName:OSS_BucketName
//            withObjectKey:objectKey];
//             NSLog(@"objectKey: %@", task.result);
//            if (!task.error) {
//                if (successBlock) {
//                    successBlock(task.result);
//                }
////                [QMUITips showSucceed:@"视频上传成功"];
//            } else {
//                NSLog(@"upload object failed, error: %@" , task.error);
////                [QMUITips showError:@"视频上传失败"];
//                if (errorBlock) {
//                    errorBlock();
//                }
//            }
//            return nil;
//        }];
//}
//取消上传
+ (void)cancel_upload {
    [OSSTask cancelledTask];//取消上传
}
@end
